package com.hup.minicontroller.client.service;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.util.Log;

import com.hup.minicontroller.client.ClientApplication;
import com.hup.minicontroller.client.model.AppState;
import com.hup.minicontroller.client.mvp.IMainView;
import com.hup.minicontroller.common.framework.SubThreadHandler;

import java.util.Set;

/**
 * 蓝牙设备服务;
 * .目前只有获取已绑定设备的功能
 * .可以在此类实现设备扫描和匹配功能
 *
 * @author hugan
 * @date 2021/5/19
 */
public class BluetoothDeviceService {
    private static final String TAG = BluetoothDeviceService.class.getSimpleName();

    private final BluetoothAdapter bluetoothAdapter;
    private final SubThreadHandler handler;
    private final AppState appState;
    private boolean isStart;

    BluetoothDeviceService() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        appState = ClientApplication.getBean(MainService.class).getAppState();
        handler = ClientApplication.getBean(SubThreadHandler.class);
    }

    public void switchService(boolean isStart) {
        if (bluetoothAdapter == null || this.isStart == isStart) return;//不支持蓝牙
        Log.i(TAG, "switchService: " + isStart);
        this.isStart = isStart;
        if (isStart) {
            handler.post(new DeviceNotifier());
        }
    }

    public void doTerminate() {
        if (bluetoothAdapter == null) return;//不支持蓝牙
        isStart = false;
    }


    private class DeviceNotifier implements Runnable {

        @Override
        public void run() {
            if (!isStart || appState.getConnectedType() != null) {
                Log.i(TAG, "run: 停止刷新蓝牙设备");
                isStart = false;
                return;
            }
            Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
            ClientApplication.executeIfExist(IMainView.class, i -> i.onScannedBluetooth(bondedDevices));
            if (isStart) handler.postDelayed(this, 3000);
        }
    }

}
